import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * PaddleOCR API 安卓客户端示例
 * 该类演示如何从安卓应用调用OCR API服务
 */
public class PaddleOCRApiClient {
    private static final String TAG = "PaddleOCRApiClient";
    private static final String API_BASE_URL = "http://your-server-ip:8000";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
    
    private final OkHttpClient client = new OkHttpClient();
    
    /**
     * OCR识别结果数据类
     */
    public static class OCRResult {
        public String text;
        public float confidence;
        public List<List<Integer>> box;
        
        @Override
        public String toString() {
            return "文本: " + text + ", 置信度: " + confidence;
        }
    }
    
    /**
     * 使用Base64编码的图像发送OCR识别请求
     * 
     * @param bitmap 要识别的图像
     * @param callback 结果回调
     */
    public void recognizeWithBase64(Bitmap bitmap, final OCRCallback callback) {
        // 将图像转换为Base64
        String base64Image = bitmapToBase64(bitmap);
        if (base64Image == null) {
            callback.onFailure("图像编码失败");
            return;
        }
        
        try {
            // 构建请求JSON
            JSONObject jsonRequest = new JSONObject();
            jsonRequest.put("image_base64", base64Image);
            jsonRequest.put("return_annotated", true);
            
            // 构建请求
            Request request = new Request.Builder()
                    .url(API_BASE_URL + "/api/recognize/base64")
                    .post(RequestBody.create(jsonRequest.toString(), JSON))
                    .build();
            
            // 执行请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    callback.onFailure("网络请求失败: " + e.getMessage());
                }
                
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        callback.onFailure("请求失败: " + response.code());
                        return;
                    }
                    
                    try {
                        // 解析响应
                        String responseBody = response.body().string();
                        JSONObject jsonResponse = new JSONObject(responseBody);
                        
                        // 处理OCR结果
                        List<OCRResult> results = parseOCRResults(jsonResponse.getJSONArray("results"));
                        
                        // 解析标注后的图像
                        String annotatedBase64 = null;
                        if (jsonResponse.has("annotated_image_base64")) {
                            annotatedBase64 = jsonResponse.getString("annotated_image_base64");
                        }
                        
                        // 回调结果
                        callback.onSuccess(results, annotatedBase64);
                    } catch (JSONException e) {
                        callback.onFailure("解析响应失败: " + e.getMessage());
                    }
                }
            });
        } catch (JSONException e) {
            callback.onFailure("构建请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过文件上传方式发送OCR识别请求
     * 
     * @param imageFile 图像文件
     * @param callback 结果回调
     */
    public void recognizeWithFile(java.io.File imageFile, final OCRCallback callback) {
        // 构建MultipartBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", imageFile.getName(),
                        RequestBody.create(imageFile, MEDIA_TYPE_IMAGE))
                .addFormDataPart("return_annotated", "true")
                .build();
        
        // 构建请求
        Request request = new Request.Builder()
                .url(API_BASE_URL + "/api/recognize")
                .post(requestBody)
                .build();
        
        // 执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure("网络请求失败: " + e.getMessage());
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.onFailure("请求失败: " + response.code());
                    return;
                }
                
                try {
                    // 解析响应
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    
                    // 处理OCR结果
                    List<OCRResult> results = parseOCRResults(jsonResponse.getJSONArray("results"));
                    
                    // 获取图像URL
                    String originalImageUrl = jsonResponse.optString("original_image_url");
                    String annotatedImageUrl = jsonResponse.optString("annotated_image_url");
                    String annotatedBase64 = jsonResponse.optString("annotated_image_base64");
                    
                    // 回调结果
                    callback.onSuccess(results, annotatedBase64);
                } catch (JSONException e) {
                    callback.onFailure("解析响应失败: " + e.getMessage());
                }
            }
        });
    }
    
    /**
     * 解析OCR识别结果
     */
    private List<OCRResult> parseOCRResults(JSONArray jsonArray) throws JSONException {
        List<OCRResult> results = new ArrayList<>();
        
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject item = jsonArray.getJSONObject(i);
            
            OCRResult result = new OCRResult();
            result.text = item.getString("text");
            result.confidence = (float) item.getDouble("confidence");
            
            if (item.has("box") && !item.isNull("box")) {
                result.box = new ArrayList<>();
                JSONArray boxArray = item.getJSONArray("box");
                
                for (int j = 0; j < boxArray.length(); j++) {
                    JSONArray pointArray = boxArray.getJSONArray(j);
                    List<Integer> point = new ArrayList<>();
                    point.add(pointArray.getInt(0));
                    point.add(pointArray.getInt(1));
                    result.box.add(point);
                }
            }
            
            results.add(result);
        }
        
        return results;
    }
    
    /**
     * 将Bitmap转换为Base64字符串
     */
    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            return Base64.encodeToString(byteArray, Base64.NO_WRAP);
        } catch (Exception e) {
            Log.e(TAG, "Bitmap转Base64失败: " + e.getMessage());
            return null;
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "关闭流失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * OCR识别结果回调接口
     */
    public interface OCRCallback {
        void onSuccess(List<OCRResult> results, String annotatedImageBase64);
        void onFailure(String message);
    }
    
    // 使用示例
    public void exampleUsage() {
        // 假设已有一个Bitmap对象
        Bitmap imageBitmap = null; // 从相机或相册获取
        
        // 使用Base64方式识别
        recognizeWithBase64(imageBitmap, new OCRCallback() {
            @Override
            public void onSuccess(List<OCRResult> results, String annotatedImageBase64) {
                // 处理识别结果
                for (OCRResult result : results) {
                    Log.d(TAG, "识别文本: " + result.text + ", 置信度: " + result.confidence);
                }
                
                // 处理标注后的图像
                if (annotatedImageBase64 != null) {
                    byte[] decodedBytes = Base64.decode(annotatedImageBase64, Base64.DEFAULT);
                    Bitmap annotatedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
                    // 在UI中显示标注后的图像
                }
            }
            
            @Override
            public void onFailure(String message) {
                Log.e(TAG, "OCR识别失败: " + message);
            }
        });
    }
} 